package j.nawks.wx.servlet;

import j.nawks.wx.api.message.support.WeixinConstant;
import j.nawks.wx.api.persistence.DataPeristence;
import j.nawks.wx.api.persistence.mock.DefaultMockAdapter;
import j.nawks.wx.api.process.ProcessBus;
import j.nawks.wx.api.utils.WeixinUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class WxServlet extends HttpServlet {

	private String token;
	private String filesystemPath;
	private final static String TOKEN = "token";
	private final static String FILESYSTEM_PATH = "MOPAAS_FILESYSTEM17189_LOCAL_PATH";

	private DataPeristence dp;

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.token = config.getInitParameter(TOKEN);
		this.filesystemPath = System.getenv(FILESYSTEM_PATH);
		// this.dp = new MopaasAdapter();
		this.dp = new DefaultMockAdapter();
		System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		this.dp.log("系统初始化成功!!!", null);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("认证");
		// 微信首次和应用连接时需要校验信息
		PrintWriter pw = resp.getWriter();
		if (WeixinUtils.isReqLegel(req, token)) {
			// 将接收到的字符串echo反显回去
			pw.write(req.getParameter(WeixinConstant.PARAM_ECHOSTR));
		} else {
			pw.write("Exception!!!");
		}
		pw.flush();
		pw.close();

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<");
		resp.setCharacterEncoding("UTF-8");

		String requestXML = readRequestXML(req);

		PrintWriter pw = resp.getWriter();
		if (WeixinUtils.isReqLegel(req, token)) {
			System.out.println("接收到一条合法的微信消息!!!");
			pw.write(ProcessBus.getInstance().process(requestXML));
		} else {
			System.out.println("接收到一条非法的微信消息!!!");
			ProcessBus.getInstance().process(requestXML);
			pw.write("GoGoGo, not legel message");
		}
		pw.flush();
		pw.close();
	}

	private String readRequestXML(HttpServletRequest request) {
		byte[] buffer = new byte[1024];
		InputStream ins = null;
		StringBuilder sb = new StringBuilder();

		try {
			ins = request.getInputStream();
			int readSize = 0;
			while ((readSize = ins.read(buffer)) > 0) {
				sb.append(new String(buffer, 0, readSize, "utf-8"));
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

}
